#include "tile.h"



/*
 * loads tile bitmaps into mW_tiles
 * Returns 1 on success, 0 on failure
 */
int mW_tiles_load (char * tiles_source_dir)
{

	int tile_i;
	int tiles_source_dir_len;
	int tile_filename_len;
	
	char filename[256];
	
	
	tiles_source_dir_len = strlen(tiles_source_dir);
	if (tiles_source_dir_len > 255)
		return 0;
	
	
	for (tile_i = 0; tile_i < mW_NUM_TILES; tile_i++)
	{
		
		tile_filename_len = strlen(mW_tile_id_to_filename(tile_i));
		if (tiles_source_dir_len + tile_filename_len > 255)
		{
			#if DEBUG == 1
				printf("tile filename was too long\n");
			#endif
			return 0;
		}
		
		memset(&filename, 0, 256);
		strcpy(filename, tiles_source_dir);
		memcpy(&filename[tiles_source_dir_len], mW_tile_id_to_filename(tile_i), tile_filename_len);
		
		mW_tiles[tile_i] = load_bitmap((const char *) &filename, NULL);
		
		if (mW_tiles[tile_i] == NULL)
		{
			#if DEBUG == 1
				printf("There was an error loading the bitmap\n");
			#endif
			return 0;
		}
			
			
	}
	
	
	return 1;
	
}



/*
 * initializes mW_tiles, allocating memory
 */
int mW_tiles_init ()
{
	
	mW_tiles_no_tile = load_bitmap("data/interface_imgs/no_tile.bmp", NULL);
	if (mW_tiles_no_tile == NULL)
		mW_error("Error loading mW_tiles_no_tile\n");
	
	mW_tiles = (BITMAP **) malloc(sizeof(BITMAP *) * mW_NUM_TILES);
	if (mW_tiles == NULL)
		return 0;
		
	mW_tile_map_nonpassable = load_bitmap("data/interface_imgs/map_nonpassable.bmp", NULL);
	if (mW_tile_map_nonpassable == NULL)
		mW_error("failed to load nonpassable tile");
		
	mW_tile_map_passable = load_bitmap("data/interface_imgs/map_passable.bmp", NULL);
	if (mW_tile_map_passable == NULL)
		mW_error("failed to load passable tile");
		
	mW_tile_speech_bubble = load_bitmap("data/interface_imgs/speech_bubble.bmp", NULL);
	if (mW_tile_map_passable == NULL)
		mW_error("failed to load passable tile");
	
	
	return 1;
	
}



/*
 * translate a tile_id to a filename corresponding to the tile bitmap
 */
char * mW_tile_id_to_filename (const short tile_id)
{

	switch (tile_id)
	{
		
		case 11 :
			return "11_dirtgrass_90.bmp";
		case 10 :
			return "10_grass.bmp";
		case 13 :
			return "13_dirtgrass_180.bmp";
		case 14 :
			return "14_grass_rock.bmp";
		case 12 :
			return "12_dirt.bmp";
		case 1 :
			return "1_grass_in_dirt_180.bmp";
		case 0 :
			return "0_grass_in_dirt_90.bmp";
		case 3 :
			return "3_dirt_in_grass_90.bmp";
		case 2 :
			return "2_grass_in_dirt_270.bmp";
		case 5 :
			return "5_dirt_in_grass_180.bmp";
		case 4 :
			return "4_grass_in_dirt.bmp";
		case 7 :
			return "7_dirt_in_grass_270.bmp";
		case 6 :
			return "6_dirtgrass.bmp";
		case 9 :
			return "9_dirtgrass_270.bmp";
		case 8 :
			return "8_dirt_in_grass.bmp";
			
	}
	
	return NULL;
	
}
